<script setup lang='ts'>
import { ref, onMounted } from 'vue'
import { reqGetUserInfo, reqUpdateUserInfo, reqDeleteUser, reqDeblockUser } from '../../apis/user'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { User } from '../../apis/user/type'

const newPassword = ref<string>('')
const loading = ref(false)
const dialogVisible = ref(false)
const currentUser = ref<User>({} as User)
const userList = ref<User[]>([])
const searchForm = ref({
  username: '',
  role: ''
})

const pageData = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

const getUsers = async () => {
  loading.value = true
  try {
    const res = await reqGetUserInfo(pageData.value.page, pageData.value.pageSize, searchForm.value.username, searchForm.value.role)
    if (res.code === 200) {
      userList.value = res.data.records
    }
    pageData.value.total = res.data.total
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pageData.value.page = 1
  getUsers()
}

const handleReset = () => {
  searchForm.value = { username: '', role: '' }
  pageData.value.page = 1
  getUsers()
}

const handlePageChange = (newPage: number) => {
  pageData.value.page = newPage
  getUsers()
}

const handlePageSizeChange = (newPageSize: number) => {
  pageData.value.pageSize = newPageSize
  pageData.value.page = 1
  getUsers()
}

const handleEdit = (row: User) => {
  currentUser.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!currentUser.value?.username) {
    ElMessage.warning('请输入用户名')
    return
  }

  if (!currentUser.value?.email) {
    ElMessage.warning('请输入邮箱')
    return
  }

  await ElMessageBox.confirm(`确认修改用户 ${currentUser.value.username} 的信息吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    // const res = await reqUpdateUserInfo(currentUser.value.id, currentUser.value)
    const res = await reqUpdateUserInfo(currentUser.value.id, {
      username: currentUser.value?.username,
      email: currentUser.value?.email,
      role: currentUser.value?.role,
      password: newPassword.value ? newPassword.value : undefined
    })
    if (res.code === 200) {
      ElMessage.success('修改成功')
      dialogVisible.value = false
      getUsers()
    }
  })


}

const handlerDelete = async (row: User) => {
  ElMessageBox.confirm(`确认封禁用户 ${row.username} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    const res = await reqDeleteUser(row.id)
    if (res.code === 200) {
      getUsers()
      ElMessage.success('删除成功')
    }
  })
}

const handlerDeblock = async (row: User) => {
  ElMessageBox.confirm(`确认解封用户 ${row.username} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    const res = await reqDeblockUser(row.id)
    if (res.code === 200) {
      getUsers()
      ElMessage.success('解封成功')
    }
  })
}

onMounted(() => {
  getUsers()
})
</script>

<template>
  <el-card style="margin-bottom: 20px;">
    <h1 style="font-weight: 600;">用户管理</h1>
  </el-card>

  <el-card class="user-manage">
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="用户名">
        <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="角色">
        <el-select v-model="searchForm.role" placeholder="请选择角色" clearable style="width: 130px;">
          <el-option label="管理员" value="admin">
            <el-tag type="danger">admin</el-tag>
          </el-option>
          <el-option label="普通用户" value="user">
            <el-tag type="primary">user</el-tag>
          </el-option>
          <template #label>
            <el-tag :type="searchForm.role === 'admin' ? 'danger' : 'primary'">{{ searchForm.role === 'admin' ? 'admin'
              :
              'user' }}</el-tag>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="userList" border stripe>
      <el-table-column prop="id" label="用户ID" width="180" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="role" label="角色">
        <template #default="{ row }">
          <el-tag :type="row.role === 'admin' ? 'danger' : 'primary'">
            {{ row.role }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" class="ml-2" @click="handlerDelete(row)"
            v-if="row.status === 'normal'">封禁</el-button>
          <el-button type="success" size="small" class="ml-2" @click="handlerDeblock(row)" v-else>解封</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination class="mt-4" background layout="total, sizes, prev, pager, next, jumper" :total="pageData.total"
      v-model:current-page="pageData.page" v-model:page-size="pageData.pageSize" @current-change="handlePageChange"
      @size-change="handlePageSizeChange" :page-sizes="[5, 10, 20, 50]" />
  </el-card>

  <el-dialog v-model="dialogVisible" title="编辑用户信息" width="30%">
    <el-form :model="currentUser" label-width="80px" v-if="currentUser">
      <el-form-item label="用户名">
        <el-input v-model="currentUser.username" />
      </el-form-item>
      <el-form-item label="角色">
        <el-radio-group v-model="currentUser.role">
          <el-radio label="admin">管理员</el-radio>
          <el-radio label="user">普通用户</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="currentUser.email" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="newPassword"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang='scss'>
.user-manage {
  .search-form {
    margin-bottom: 20px;

    .el-form-item {
      margin-right: 20px;
      margin-bottom: 0;
    }
  }

  :deep(.el-table) {
    margin-top: 15px;
  }

  .ml-2 {
    margin-left: 8px;
  }

  .el-pagination {
    justify-content: center;
    margin-top: 20px;
  }
}
</style>